package org.example.core.utils;

import cn.hutool.core.io.resource.Resource;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.plugin.table.LoopColumnTableRenderPolicy;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.deepoove.poi.policy.RenderPolicy;
import org.apache.poi.ss.usermodel.Workbook;
import org.example.core.enums.ApiResult;
import org.example.core.exception.ErrorException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Description: 文档工具类
 * Date: 2024/1/30 21:33
 */
public class DocumentUtil {

    /**
     * 生成doc
     *
     * @param resource     模版资源
     * @param params       参数
     * @param outputStream 输出流
     */
    public void generateDoc(Resource resource, Map<String, Object> params, OutputStream outputStream) {
        InputStream stream = resource.getStream();

        ConfigureBuilder builder = Configure.builder();
        Set<String> keys = new HashSet<>(params.keySet());
        keys.forEach(key -> {
            Object value = params.get(key);
            if (value instanceof Collection) {
                RenderPolicy renderPolicy;
                if (key.contains("-row")) {
                    renderPolicy = new LoopRowTableRenderPolicy();
                } else if (key.contains("-column")) {
                    renderPolicy = new LoopColumnTableRenderPolicy();
                } else {
                    throw new ErrorException("key: " + key + " 不支持的循环方式");
                }

                String newKey = key.substring(0, key.lastIndexOf("-"));
                params.put(newKey, params.remove(key));
                builder.bind(newKey, renderPolicy);
            }
        });

        try {
            XWPFTemplate.compile(stream, builder.build()).render(params).writeAndClose(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将文件写入响应
     *
     * @param response
     * @param workbook
     * @param fileName
     * @throws IOException
     */
    public static void response(HttpServletResponse response, Workbook workbook, String fileName) throws IOException {
        try {
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.close();
            out.flush();
        } catch (Exception ex) {
            ApiResult result = ApiResult.failure(ex.getMessage());
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().print(result.getMsg());
            response.flushBuffer();
        }
    }
}
